import pygame
import Game

from pygame.locals import *
from sys import exit

#parameters
screenresulotion = (460, 280)
gridimagesize = (220, 220)
gridimagepos = (220, 20)
gridoffset = (10,10)
gridmargin = 50
pieceimagesize = 50
piecehothalfsize = 25


#functions
def GetPositionInScreen(x, y):
    return (gridimagepos[0] + gridoffset[0] + x * gridmargin, gridimagepos[1] + gridoffset[1] + y * gridmargin )

def GetImagePositionInScreen(x, y):
    pos = GetPositionInScreen(x, y)
    return (pos[0] - pieceimagesize/2, pos[1] - pieceimagesize/2)

def HitTest(cursorpos):
    if cursorpos[0] < gridimagepos[0] or cursorpos[0] > gridimagepos[0] + gridimagesize[0] or cursorpos[1] < gridimagepos[1] or cursorpos[1] > gridimagepos[1] + gridimagesize[1]:
        return None
    px = (cursorpos[0] - (gridimagepos[0] + gridoffset[0] - piecehothalfsize))/gridmargin
    py = (cursorpos[1] - (gridimagepos[1] + gridoffset[1] - piecehothalfsize))/gridmargin
    return (px, py)

def IsInGridRange(pos):
    return pos[0]>=gridimagepos[0] and pos[0]<=gridimagepos[0] + gridimagesize[0] and pos[1] >=gridimagepos[1] and pos[1] <= gridimagepos[1] + gridimagesize[1]

def PosToPiecePosition(pos):
    res = Game.pieceposition()
    res.x = pos[0]
    res.y = pos[1]
    return res



#init
game = Game.game()
pygame.init()
pygame.font.init()

titlefont = pygame.font.SysFont(None, 20)

#Screen and title
screen = pygame.display.set_mode(screenresulotion, 0, 32)
pygame.display.set_caption("Stick and Stones")
grid = pygame.image.load("images/grid.png").convert_alpha()
stone = pygame.image.load("images/stone.png").convert_alpha()
stick = pygame.image.load("images/stick.png").convert_alpha()
stone_s = pygame.image.load("images/stone_s.png").convert_alpha()
stick_s = pygame.image.load("images/stick_s.png").convert_alpha()

#game.ground[1][2] = Game.piece_p1
#game.ground[1][3] = Game.piece_p2
#game.ground[1][4] = Game.piece_p1_catch_p2
#game.ground[2][2] = Game.piece_p2_catch_p1

#Operation Parameters
selectedpos = (-1, -1)
pickedpiece = Game.piece_empty


def DrawPiece(piece, pos, selected):
    if piece == Game.piece_p1:
        if selected:
            screen.blit(stone_s, pos)
        else:
            screen.blit(stone, pos)
    elif piece == Game.piece_p2:
        if selected:
            screen.blit(stick_s, pos)
        else:
            screen.blit(stick, pos)
    elif piece == Game.piece_p1_catch_p2:
        screen.blit(stick, pos)
        screen.blit(stone, pos)
    elif piece == Game.piece_p2_catch_p1:
        screen.blit(stone, pos)
        screen.blit(stick, pos)

def GetOperationString():
    if game.state == Game.state_input:
        return 'Set piece'
    elif game.state == Game.state_move:
        return 'Move piece'
    elif game.state == Game.state_catch:
        return "Catch other's {} pieces".format(game.stateparam)
    elif game.state == Game.state_eat:
        return "Eat other's {} pieces".format(game.stateparam)
    else:
        return "Over. Player {} win.".format(game.curplayer)
#message loop
while True:
    event = pygame.event.wait()
    if event.type == QUIT:
        exit()

    pressed_mouse = pygame.mouse.get_pressed()
    mousepos = pygame.mouse.get_pos()

    #Background and Grid
    screen.fill((255,255,255))
    screen.blit(grid, gridimagepos)

    #Ground
    for i in range(5):
        for k in range(5):
            if not (selectedpos and selectedpos[0] == i and selectedpos[1]==k):
                DrawPiece(game.ground[i][k], GetImagePositionInScreen(i, k), False)

    #Mouse Operations
    if game.state == Game.state_input:
        pickedpiece = game.curplayer
        if pressed_mouse[0]:
            targetpos = HitTest(mousepos)
            if targetpos:
                game.SetPiece(PosToPiecePosition(targetpos))
                pickedpiece = Game.piece_empty

    elif game.state == Game.state_catch:
        pickedpiece = Game.piece_empty
        if pressed_mouse[0]:
            targetpos = HitTest(mousepos)
            if targetpos:
                game.Catch(PosToPiecePosition(targetpos))

    elif game.state == Game.state_move:
        if game.IsSomePieceMoveAble():
            if pickedpiece and pickedpiece != Game.piece_empty:
                if pressed_mouse[0]:
                    targetpos = HitTest(mousepos)
                    if targetpos:
                        curplayer = game.curplayer
                        game.Move(PosToPiecePosition(selectedpos), PosToPiecePosition(targetpos))
                        selectedpos = None
                        pickedpiece = None
            else:
                if pressed_mouse[0]:
                    targetpos = HitTest(mousepos)
                    if targetpos and game.ground[targetpos[0]][targetpos[1]] == game.curplayer:
                        selectedpos = targetpos
                        pickedpiece = game.curplayer
                    else:
                        selectedpos = None
                        pickedpiece = None
        else:
            game.SwapPlayer()

    elif game.state == Game.state_eat:
        pickedpiece = Game.piece_empty
        if pressed_mouse[0]:
            targetpos = HitTest(mousepos)
            if targetpos:
                game.Eat(PosToPiecePosition(targetpos))
    else:
        pickedpiece = None

    #picked piece
    if pickedpiece and IsInGridRange(mousepos):
        DrawPiece(pickedpiece, (mousepos[0] - pieceimagesize/2, mousepos[1] - pieceimagesize/2), True)


    #Current Player
    cp_surface = titlefont.render("Current Player: Player {}".format(game.curplayer), True, (0,0,0))
    screen.blit(cp_surface, (10, gridimagepos[1] + 20))
    DrawPiece(game.curplayer, (30, gridimagepos[1] + 20+ 20), False)

    op_surface = titlefont.render("Operation: {}".format(GetOperationString()), True, (0,0,0))
    screen.blit(op_surface, (10, gridimagepos[1] + 20 + 50 + 10+ 20))

    pygame.display.update()

